(function($){

	function Model() {
		this.form = null;
		this.submitButton = null;

		this.formData = new Array();
		this.submitButtonName = null;

		this.errorMessages = new Array();
	}

	/**************************
	 * Initialization
	 **************************/

	Model.prototype.run = function () {
		controller.debug ("Model.run()");
	}
	
	/**************************
	 * Form Processing
	 **************************/

	Model.prototype.saveFormData = function(form, submitButton) {
		form.find("input, textarea, select").each(function() {
			var element = $(this);
			if (element.is("input")) {
				var name = element.attr("name")
				model.formData[name] = element.val();
			} else {
		}
		});
		model.submitButton = submitButton;
		model.submitButtonName = submitButton.attr("name");
		model.form = form;
	}

	Model.prototype.fetchData = function (url, data, fn_success) {
		$.ajax({
			'url':url,
			'data':data,
			'type': 'post',
			'dataType': 'json',
			'success': function(json) {
				if (json && json.response && json.response == "error") {
					presenter.setModalContent("<h2>" + json.errortype + "</h2><p>" + json.errormessage + "</p>");
					presenter.showModal();
					controller.relocateTo("#/");
				} else if (json && json.response && json.response == "ok") {
					fn_success(json);
				} else {
					presenter.setModalContent("<h2>Error</h2><p>No content was returned from the server.</p>");
					presenter.showModal();
					controller.relocateTo("#/");
				}
			},
			'error': function(error) {
				controller.log ("JSMVPC ERROR: Ajax call failed. Likely malformatted JSON.");
				controller.relocateTo("#/");
			}
		});
	}

	Model.prototype.getErrorMessages = function() {
		return this.errorMessages;
	}

	Model.prototype.clearErrors = function() {
		this.errorMessages.empty();
	}

	Model.prototype.addError = function(message) {
		this.errorMessages.put(message);
	}

	/**************************
	 * For office use only
	 **************************/

	window.model = new Model();

	return(window.model);

})(jQuery);